package edu.qichen.onlineBlog.email.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import edu.qichen.onlineBlog.framework.DataResult;
import edu.qichen.onlineBlog.framework.OperationAnnotation;
import edu.qichen.onlineBlog.framework.exception.ErrorCodeEnum;
import edu.qichen.onlineBlog.email.service.MailService;
import edu.qichen.onlineBlog.framework.utils.RedisUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * 功能:邮件
 * 作者:程序员欧阳子韩
 * 日期:2024/4/19 16:04
 */
@RestController
@Slf4j
@RequestMapping("/email")
@Tag(name = "邮件接口")
public class MailController {
    @Autowired
    private MailService mailService;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 获取验证码
     *
     * @param email -
     * @return -
     */
    @Operation(summary = "获取验证码")
    @RequestMapping("/code")
    @OperationAnnotation(content = "获取验证码", sysType = 0, opType = 4, action = "成功")
    public DataResult<?> sendMail(String email, HttpServletRequest request) {
        // key 邮箱号  value 验证码
        String code = (String) redisUtils.get(email);

        // 从redis获取验证码，如果获取获取到，提示已经获取验证码，请稍后再获取
        if (!StrUtil.isEmpty(code)) {
            return DataResult.fail(ErrorCodeEnum.CODE_NOT_EMPTY);
        }

        // 如果从redis获取不到，生成新的6位验证码
        code = RandomUtil.randomNumbers(6);

        boolean isSend = mailService.sendMail(email, code);

        if (isSend) {
            // 生成验证码放到redis里面，设置有效时间为5分钟
            redisUtils.set(email, code, 5 * 60);
            return DataResult.success("获取验证码成功，请查看邮箱");
        }

        HttpSession session = request.getSession();
        session.setAttribute("username", "获取验证码");
        return DataResult.fail(ErrorCodeEnum.SYSTEM_ERROR);
    }
}
